package EGS.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import com.google.gson.Gson;

import ORDER.c_order;
import ORDER.orderManagement;
import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import TOYS.LASERUPH.laserUPHreporter;
import WORKPLACE.URLapi;
import WORKPLACE.stationClient;

public class EGS_execute_service580Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 580 激活工单
	 */
	public EGS_execute_service580Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		String msgClass = "";
		try {
			if (MSG == null) {
				return null;
			}
			Element Mroot = MSG.getRootElement();
			msgClass = Mroot.element("header").attribute("messageClass").getValue();
			String iStation,  iLayer;
			int iiLayer;

			iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();

			if (msgClass.equals("580")) {// 试运行阶段二，用580的时机来切换工单到对应工位。
				String lv2Key = "orderInfo";
				String orderNo = null;
				try {
					orderNo = Mroot.element("body").element(lv2Key).attribute("order_no").getValue();// iSN=modelNo
				} catch (Exception e) {
					lv2Key = "modelInfo";
					;
				}
				if (orderNo == null) {
					orderNo = "";
				}
				iLayer = Mroot.element("body").element(lv2Key).attribute("side").getValue();
				iiLayer = Integer.parseInt(iLayer);
				Mroot.remove(Mroot.element("body"));
				Element eleB = Mroot.addElement("body");
				Element eleR = eleB.addElement("result");

				String str = "SELECT a.* FROM vOrderList_new a  \r\n" + 
						"LEFT JOIN product_struct b ON b.masterNumber=a.partNumber   \r\n" + 
						"where (a.orderNumber='"+orderNo+"')   and b.isMarked=1 \r\n" + 
						"UNION\r\n" + 
						"SELECT a.* FROM vOrderList_new a  \r\n" + 
						"LEFT JOIN product_struct b ON b.masterNumber=a.partNumber   \r\n" + 
						"where (a.panelOrderNumber='"+orderNo+"')   and b.isMarked=1 ";
				JTable t = sql.select(str);
				int isMarked = 0;
				if (t != null && t.getRowCount() > 0) {
					isMarked = 1;
				}

				if(orderNo==null || orderNo.length()<1) {
					str = "工单号获取失败，请检查激活软件版本";
					eleR.addAttribute("isMarked", "" + isMarked);
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", "0");
					AKSLogs(5800, "" + orderNo + "_" +iStation + ":_" + str);
				}else {
					try {
						if (iClient.myProcedureNumber.equals("A0010")) {// 检查条码是否发行到指定数量（计划+追加）
							if (orderNo != null && orderNo.length() > 0) {
								new Thread(new Runnable() {// 每个工单都要按照非必过站设置SN初始状态
									String oldOrder= iClient.activeOrderNumber;
									@Override
									public void run() {
										
										try {
											laserUPHreporter lr=new laserUPHreporter(sql);
											lr.updateReport(oldOrder);
										} catch (Exception e) {
											;
										}
									}
								}).start();
							}
						}
						if (iClient.myProcedureNumber.equals("A0060")) {// 检查过期料是否确认完毕
							if (orderNo != null && orderNo.length() > 0 && !orderNo.equals(iClient.activeOrderNumber)) {
								str="select * from ML.vExpireOnLine where orderNumber='"+iClient.activeOrderNumber+"'";
								t=sql.select(str);
								if(t!=null && t.getRowCount()>0) {
									throw new Exception("换线失败，前一个工单"+iClient.activeOrderNumber+"有过期料未确认");
								}
								
							}
						}
						c_order co=new c_order(sql);
    					co.checkOrderState(orderNo);
						
						iClient.changeStationOrder(orderNo, iiLayer, 0);
						if (iClient.myProcedureNumber.equals("A0010")) {// 检查条码是否发行到指定数量（计划+追加）
							if (orderNo != null && orderNo.length() > 0) {
								// 根据工单获取相关刻码规则信息，检查刻码规则是否已审核
		    					co.checkSNtoolReleaseFlag(orderNo, "A0010");// 抛出刻码规则未审核的异常 
								String gOrderNumber = orderNo;
								new Thread(new Runnable() {// 每个工单都要按照非必过站设置SN初始状态
									String mgOrderNumber = gOrderNumber;
									@Override
									public void run() {
										try {
											orderManagement om = new orderManagement(sql);
											om.createSN4order(mgOrderNumber);
										} catch (Exception e) {
											;
										}
									}
								}).start();
								
								sql.Command("delete from [QM].[temp10000_laserInspec] "
										+ "where stationID='"+iStation+"' ");
								JTable maxCounterT=sql.select("select olp.panelNumber,isnull(pli.activeQty,5) "
										+ "from [dbo].[order_list_panel] olp \r\n" + 
										"LEFT JOIN [QM].[vPanelLaserInspec] pli ON pli.panelNumber=olp.panelNumber \r\n" + 
										"where panelOrderNumber='"+orderNo+"' ");
								String maxCounter=""+maxCounterT.getValueAt(0, 1);
								// 激活成功，重置计数器和计时器  
								String strSQL1="update [dbo].[assetStation] "
										+ "set counter=0,maxCounter="+maxCounter+",lastCheck=null,EMflag=0,QCflag=0 "
										+ "where ID='"+iStation+"' ";
								sql.Command(strSQL1);
							}
						}else if (iClient.myProcedureNumber.equals("A0040")) {// 230703配合香振炉温板软件 
							String strSQL1="select name from dbo.assetLine where ID="+iClient.myLineID;
							JTable lineNameT=sql.select(strSQL1);
							String iLine=(""+lineNameT.getValueAt(0, 0)).split("-")[1];
							JTable t1=sql.select("select panelNumber from [dbo].[order_list_panel] "
									+ "where panelOrderNumber='"
									+ orderNo + "' ");
							String iPanel=""+t1.getValueAt(0, 0);
							strSQL1="update [sunlight].[FurnaceKanbanInstructs] set WorkOrder='"
									+orderNo+"',MakeUpOrder='"+iPanel+"' where line="+Integer.parseInt(iLine);
							sql.Command(strSQL1);
						}
						new Thread(new Runnable() {
							
							@Override
							public void run() {
								try {
									iClient.freshOrderWipQty_station(iStation);
								} catch (Exception e1) {
									;
								}
							}
						}).start();
						eleR.addAttribute("isMarked", "" + isMarked);
						eleR.addAttribute("errorCode", "0");
						eleR.addAttribute("errorText", "Valid");
						eleR.addAttribute("actionCode", "0");
						
						try {//TODO 增加OEE开始统计API
							URLapi aa=new URLapi();
							aa.RESTInvoker("http://192.168.0.220:8081", "","");
							Map<String,Object> poster=new HashMap<>();
							poster.put("stationId", iStation);
							String ijson=new Gson().toJson(poster);
							aa.postDataToServer("/api/order/productionReport/createStartMsg4Oee", ijson,aa.getToken());
						} catch (Exception e) {
							;//避免order模块重启导致的停线
						}
						AKSLogs(5801, "" + orderNo + "_" + iStation + "_" + iLayer);
					} catch (Exception e) {
						try {
							String str1=e.getMessage();
							if(str1.split("@")[0].equals("-184")) {
								throw new Exception(""+str1.split("@")[1]+"的刻码规则未审核");
							}
							throw e;
						} catch (Exception e1) {
							str = errCodeManagement.getErrText(e1.getMessage());
							eleR.addAttribute("isMarked", "" + isMarked);
							eleR.addAttribute("errorCode", "1");
							eleR.addAttribute("errorText", str);
							eleR.addAttribute("actionCode", "0");
							AKSLogs(5800, "" + orderNo + "_" +iStation + ":_" + str);
						}
					}
				}
				
			} else {
				isUnknowCase = true;
				return null;
			}
			return MSG;
		} catch (Exception e) {
			if(iClient==null) {
				Element Mroot = MSG.getRootElement();
				Element eleR = Mroot.element("body").addElement("result");
				eleR.addAttribute("errorCode", "1");
				eleR.addAttribute("errorText", "工位信息获取失败");
				eleR.addAttribute("actionCode", "0");
				return MSG;
			}
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			return null;
		}

	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}

}
